<template>
  <el-dialog :model-value="dialogVisible" title="分配角色" width="30%" @close="handleClose">
    <el-select v-model="adminRoleData" multiple placeholder="请选择" style="width: 240px">
      <el-option v-for="item in RoleListAll" :key="item.value" :label="item.label" :value="item.value" />
    </el-select>
    <template #footer>
      <span class="dialog-footer">
        <el-button size="large" @click="cancelFn">取 消</el-button>
        <el-button size="large" type="primary" @click="confirmFn">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { admin } from '@/request/api'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, watch } from 'vue'

const props = withDefaults(
  defineProps<{
    dialogVisible: boolean
    id: number
    RoleListAll: { value: number; label: string }[]
  }>(),
  { dialogVisible: false, id: 0 }
)
const emit = defineEmits<{
  (event: 'allotCancelFn'): void
  (event: 'allotConfirmFn'): void
}>()
// 指定用户的角色数据
const adminRoleData = ref<number[]>([])
// 获取指定用户的角色
watch(
  () => props.id,
  async () => {
    if (props.id === 0) {
      adminRoleData.value = []
    } else {
      // 更新角色权限
      let res = await admin.APIAdminRole(props.id)
      if (res.code === 200) adminRoleData.value = res.data.map((item) => item.id)
      else ElMessage.error('错误！')
    }
  }
)
// 取消 按钮
const cancelFn = () => {
  emit('allotCancelFn')
}
// 确定 按钮
const confirmFn = async () => {
  ElMessageBox.confirm('此操作将修改当前用户角色, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      let res = await admin.APIAdminRoleUpdate(props.id, adminRoleData.value.join(','))
      if (res.code === 200) {
        ElMessage.success('修改成功！')
      } else {
        ElMessage.error('修改失败！')
      }
      emit('allotConfirmFn')
    })
    .catch(() => {})
}
// Dialog 关闭的回调
const handleClose = () => {
  emit('allotCancelFn')
}
</script>

<style lang="less" scoped></style>
